$(function () {
    /* 订单列表 */
    $("#jqGrid").jqGrid({
        url: baseURL + 'order/factoryorder/sellerlist',
        datatype: "json",
        colModel: [
            { label: '订单编号', name: 'orderId', index: 'order_id', width: 120, key: true , align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" onclick="return vm.getInfo(\''+ value +'\');">'+ value +'</a>';
                }
            },
            { label: '打印', name: '', index: '', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;">购</a>'
                }},
            { label: '商品总额', name: 'totalAmount', index: 'total_amount', width: 60 , align:'center'},
            { label: '应支付额', name: 'payableAmount', index: 'payable_amount', width: 60 , align:'center'},
            { label: '已支付额', name: 'payed', index: 'payed', width: 60 , align:'center'},
            { label: '会员名', name: 'memberName', index: 'member_name', width: 100 , align:'center'},
            { label: '叫快递', name: '', index: '', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;">叫快递</a>'
                }},
            { label: '联系人', name: 'shipName', index: 'ship_name', width: 80 , align:'center'},
            { label: '客户电话', name: 'mobile', index: 'mobile', width: 70 , align:'center'},
            { label: '地址', name: 'shipAddr', index: 'ship_addr', width: 150 , align:'center'},
            { label: '下单时间', name: 'createtime', index: 'createtime', width: 120 , align:'center'},
            { label: '订单状态', name: 'statusText', index: '', width: 80 , align:'center'},
            { label: '支付状态', name: 'payStatus', index: 'pay_status', width: 80 , align:'center',
                formatter: function (value) {
                    return value == '1' ? '已支付' : '未支付';
                }
            },
            { label: '发货状态', name: 'shipStatus', index: 'ship_status', width: 80 , align:'center',
                formatter: function (value) {
                    return value == '1' ? '已发货' : '未发货';
                }
            },
            { label: '生产状态', name: 'productionStatus', index: 'production_status', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    // '生产状态:1.待审核;2.待分配;3.生产中;4.生产完成;5.已发货;6.已完成;7.新开单(门店);11.已作废',
                    if (isBlank(value) || value == '1'){
                        // 分配的订单有待接单状态
                        var allocated = row.allocated;
                        if (allocated){
                            return '待接单';
                        }else {
                            return '生产中';
                        }
                    }else if (value == '3'){
                        return '生产中';
                    }else if (value == '4'){
                        return '生产完成';
                    }else if (value == '6'){
                        return '已完成';
                    }else {
                        return '';
                    }
                }
            },
            { label: '操作', name: '', index: '', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    // 判断是否分配订单，有开始生产、生产完成操作
                    if (row.allocated){
                        var productionStatus = row.productionStatus;
                        if (productionStatus == null || productionStatus == 1){
                            return '<a href="javascript:;" onclick="return vm.produceStart(\''+ row.orderId +'\');">开始生产</a>';
                        }else if (productionStatus == 3){
                            return '<a href="javascript:;" onclick="return vm.produceFinish(\''+ row.orderId +'\');">生产完成</a>';
                        }
                    }
                    return '--';
                }
            },
        ],
        viewrecords: true,
        height: window.innerHeight - 120 ,
        rowNum: 25,
        rowList : [25,50,75],
        rownumbers: true,
        rownumWidth: 40,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            // 隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.payTypeEnum = userData.payTypeEnum;
            vm.e.orderInfoStatusEnum = userData.orderInfoStatusEnum;
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        showOrder: false,
        showLogi: false,
        orderInfo: {},
        erpOrder: {},
        orderItemList: [],
        orderLogisticsEntityList: [],
        userPaymentList: [],
        procedure: '',
        /* 枚举 */
        e:{
            productionStatusEnum: [],
            payTypeEnum: [],
            orderInfoStatusEnum: [],
            goodsTypeEnum: [],
        },
        /* 查询 */
        q:{
            orderId: '',
            memberName: '',
            productionStatus: '',
            beginCreatetime: '',
            endCreatetime: '',
            orderAuditStatus: '',
            orderPayStatus: '',
            productionStatus: '',
            status: '',
            shipStatus: ''
        },
        /* 价格详情 */
        priceTableVisible: false,
        view:{
            quoteProductInfoList: [],
            attributeValueTypeMap: '',
            paperInfoList: [],
            printType: '',
            totalCraftPrice: 0,
            totalPrintPrice: 0,
            totalTotalPrice: 0,
            sharePrice: 0,
            subtract: 0
        },
        /* 附件下载 */
        fileTableVisible: false,
        /* 源文件下载 */
        itemFile:{
            /* 订单商品集合下标标识，获得当前正在操作的商品元素 */
            itemIndex: 0,
            /* 正在操作商品的附件集合 */
            itemFiles: []
        },
        /* 添加物流 */
        showSendDetail: true,       // 是否显示发货明细
        showLogiNo: true,           // 是否显示配送单号
        erpLogisticsEntity:{},
        logisticsTypeList:[],
        /* 省市区data */
        area: [],
        oderInfoEntity:{},
        orderItemEntityList:[],
    },
    methods: {
        /* 订单起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 订单结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 获取当前日期 */
        dateFormat: function(date) {
            if (typeof date == 'string'){
                date = new Date(date);
            }
            var year=date.getFullYear();
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        /* 详情页面 */
        getInfo: function(orderId){
            $.get(baseURL + "order/orderinfo/mall/info/" + orderId, function(r){
                /* 实体类 */
                vm.erpOrder = r.erpOrder;
                vm.orderInfo = r.orderInfo;
                vm.orderItemList = r.orderItemList;
                vm.orderLogisticsEntityList = r.orderLogisticsEntityList;
                vm.userPaymentList = r.userPaymentList;
                vm.procedure = r.procedure;

                /* 枚举 */
                vm.e.addcartBuyTypeEnum = r.addcartBuyTypeEnum;
                vm.e.taxTypeEnum = r.taxTypeEnum;
                vm.e.goodsTypeEnum = r.goodsTypeEnum;

                vm.showList = false;
                vm.showLogi = false;
                vm.showOrder = true;
            });
        },
        reset: function () {
            vm.q.orderId = '';
            vm.q.memberName = '';
            vm.q.productionStatus = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.orderAuditStatus = '';
            vm.q.orderPayStatus = '';
            vm.q.productionStatus = '';
            vm.q.status = '';
            vm.q.shipStatus = '';
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        reload: function (event) {
            vm.showList = true;
            vm.showOrder = false;
            vm.showLogi = false;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'orderId': vm.q.orderId,
                    'memberName': vm.q.memberName,
                    'productionStatus': vm.q.productionStatus,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime,
                    'orderAuditStatus': vm.q.orderAuditStatus,
                    'orderPayStatus': vm.q.orderPayStatus,
                    'productionStatus': vm.q.productionStatus,
                    'status': vm.q.status,
                    'shipStatus': vm.q.shipStatus,
                },
            }).trigger("reloadGrid");
        },
        /* 价格详情 */
        priceView: function (data) {
            vm.priceTableVisible = true;
            $.get(baseURL + "order/factoryorder/orderItemInfo?itemId=" + data.itemId, function(r){
                vm.view.quoteProductInfoList = r.quoteProductInfoList;
                vm.view.attributeValueTypeMap = r.attributeValueTypeMap;
                vm.view.paperInfoList = r.paperInfoList;
                vm.view.printType = r.printType;
                vm.view.totalCraftPrice = r.totalCraftPrice;
                vm.view.totalPrintPrice = r.totalPrintPrice;
                vm.view.totalTotalPrice = r.totalTotalPrice;
                vm.view.sharePrice = r.sharePrice;
                vm.view.subtract = r.subtract;
            });
        },
        /* 展示源文件 */
        itemFileShow: function (idx) {
            var itemId = vm.orderItemList[idx].itemId;
            $.ajax({
                type: "GET",
                url: baseURL + "order/useraccessory/userAccessorys/" + itemId,
                contentType: "application/json",
                data: [],
                success: function(r){
                    if(r.code === 0){
                        var goodsName = vm.orderItemList[idx].name;
                        vm.fileTableVisible = true;
                        vm.itemFile.itemIndex = idx;
                        vm.itemFile.itemFiles = r.list;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        // 原文件下载
        itemFileDownload: function (data) {
            window.location.href = baseURL + "order/useraccessory/download/" + data.id;
        },
        // 发送物流
        send:function () {
            var that = this;
            var orderIds = getSelectedRows();
            //先去重
            orderIds = vm.removeDuplicatedItem(orderIds);
            if(orderIds == null){
                return ;
            }
            if(orderIds.length!=1){
                this.$message("请勿勾选订单号不同项");
                return ;
            }
            var orderId=orderIds[0];
            $.ajax({
                type: "GET",
                url: baseURL + "order/orderinfo/mall/sendLogisticsInfo/" + orderId,
                contentType: "application/json",
                data: null,
                success: function(r){
                    if(r.code == 0){
                        vm.oderInfoEntity = r.oderInfoEntity;
                        vm.orderItemEntityList = r.orderItemEntityList;
                        vm.area = JSON.parse(r.area);
                        vm.logisticsTypeList=r.logisticsTypeList;
                        var shipMobile = vm.oderInfoEntity.shipMobile;
                        var shipTel = vm.oderInfoEntity.shipTel;
                        var toPhone = shipMobile == null ? "" : shipMobile + "" + (shipTel == null ? "": ","+ shipTel);
                        vm.erpLogisticsEntity = {
                            toPeople: vm.oderInfoEntity.shipName,
                            toPhone:  toPhone,
                            toAddress: vm.oderInfoEntity.shipAddr,
                            toArea: vm.oderInfoEntity.shipArea,
                            toAreaId: vm.oderInfoEntity.shipAreaId,
                            sendType: 3,
                            logiType: 2
                        };

                        // 省市区信息
                        var regionPath = vm.oderInfoEntity.regionPath;
                        if (!isBlank(regionPath)){
                            // 字符型数组
                            var regionPathStringArr = regionPath.substring(1, regionPath.length-1).split(",");
                            // 整形数组
                            var regionPathIntArr = regionPathStringArr.map(function(data){
                                return + data;
                            });
                            Vue.set(vm.erpLogisticsEntity, 'areaCascader', regionPathIntArr);
                        }

                        // 发货人信息
                        $.get(baseURL + "supp/sellerinfo/info", function(r){
                            var sellerinfo = r.sellerInfo;
                            Vue.set(vm.erpLogisticsEntity, 'fromPeople', sellerinfo.sellerName);
                            Vue.set(vm.erpLogisticsEntity, 'fromPhone', sellerinfo.sellerMobile);
                            Vue.set(vm.erpLogisticsEntity, 'fromAddress', sellerinfo.addr);
                            Vue.set(vm.erpLogisticsEntity, 'fromArea', sellerinfo.area);
                        });
                        that.$refs.multipleTable.toggleAllSelection();

                        vm.showList = false;
                        vm.showOrder = false;
                        vm.showLogi = true;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        removeDuplicatedItem:function(arr){
            for(var i = 0; i < arr.length-1; i++){
                for(var j = i+1; j < arr.length; j++){
                    if(arr[i]==arr[j]){
                        arr.splice(j,1);
                        j--;
                    }
                }
            }
            return arr;
        },
        // 监听订单明细勾选change事件
        orderItemSelectionChange: function (row) {
            var list = new Array();
            for (var i = 0, orderItem; orderItem = row[i++];) {
                var logisticsItem = {
                    orderItemId: orderItem.itemId,
                    orderItemName: orderItem.name,
                    quantity: orderItem.nums,
                }
                list.push(logisticsItem);
            }
            vm.logisticsItemList = list;
        },
        saveLogistics:function () {
            // 验证参数
            if (!vm.validator()) {
                return false;
            }
            // todo校验
            var erpLogisticsDto = {
                erpLogisticsEntity: vm.erpLogisticsEntity,
                erpLogisticsItemList: vm.logisticsItemList
            }
            erpLogisticsDto.erpLogisticsEntity.orderId = vm.oderInfoEntity.orderId;
            // 暂定为一样，如需修改再改
            erpLogisticsDto.erpLogisticsEntity.orderNo = vm.oderInfoEntity.orderId;
            erpLogisticsDto.erpLogisticsEntity.sellerId = vm.oderInfoEntity.supplierId;
            erpLogisticsDto.erpLogisticsEntity.fromPeople = vm.erpLogisticsEntity.fromPeople;
            erpLogisticsDto.erpLogisticsEntity.fromArea = vm.erpLogisticsEntity.fromArea;
            erpLogisticsDto.erpLogisticsEntity.fromAddress = vm.erpLogisticsEntity.fromAddress;
            erpLogisticsDto.erpLogisticsEntity.fromPhone = vm.erpLogisticsEntity.fromPhone;
            // 防止后台校验报错
            erpLogisticsDto.erpLogisticsEntity.productionId=0;
            $.ajax({
                type: "POST",
                url: baseURL + "logistics/erplogistics/saveOrderLogisticsInfo",
                contentType: "application/json",
                data: JSON.stringify(erpLogisticsDto),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        // 参数验证
        validator: function () {
            if(vm.erpLogisticsEntity.logiType != 3){
                if (isBlank(vm.erpLogisticsEntity.logisticsId)) {
                    alert("物流方式不能为空");
                    return false;
                }
            }
            if (isBlank(vm.erpLogisticsEntity.toPeople)) {
                alert("收货人不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toAreaId)) {
                alert(" 收货地区不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toArea)) {
                alert("收货地址不能为空");
                return false;
            }
            return true;
        },
        reback: function () {
            vm.reload();
        },
        logiTypeChange: function (value) {
            for (var i = 0, logisticsType; logisticsType = vm.logisticsTypeList[i++];) {
                // 紫云物流 不填写配送单号
                if (logisticsType.logisticsId == value){
                    vm.erpLogisticsEntity.logiCompany = logisticsType.logisticsName;
                    if (logisticsType.logisticsName.indexOf("紫云-") == 0){
                        vm.showLogiNo = false;
                        break;
                    }
                }else {
                    vm.showLogiNo = true;
                }
            }
        },
        sendTypeChange: function (value) {
            if (value == 1) {
                vm.showSendDetail = false;
            } else {
                vm.showSendDetail = true;
            }
        },
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            vm.erpLogisticsEntity.toAreaId = areaId;

            var lableObj = getCascaderObj(val, vm.area);
            var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.erpLogisticsEntity.toArea = lable;
        },
        produceStart: function (orderId) {
            this.$confirm('是否确认开始生产?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/produceStart",
                            contentType: "application/json",
                            data: {
                                orderId: orderId
                            },
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        produceFinish: function (orderId) {
            this.$confirm('是否确认生产完成?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/produceFinish",
                            contentType: "application/json",
                            data: {
                                orderId: orderId
                            },
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        }
    }
});

/**
 * 省市区级联选择
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children;
                return label;
            }
        }
        return null;
    });
}
